#!/bin/bash

# 确保脚本在错误时停止
set -e

echo "开始部署Todo应用..."

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "Docker未安装，正在安装..."
    sudo apt update
    sudo apt install -y apt-transport-https ca-certificates curl software-properties-common
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
    sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
    sudo apt update
    sudo apt install -y docker-ce
fi

# 检查Docker Compose是否安装
if ! command -v docker-compose &> /dev/null; then
    echo "Docker Compose未安装，正在安装..."
    sudo curl -L "https://github.com/docker/compose/releases/download/v2.20.3/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    sudo chmod +x /usr/local/bin/docker-compose
fi

# 确保当前用户可以运行docker命令
if ! groups | grep -q docker; then
    echo "将当前用户添加到docker组..."
    sudo usermod -aG docker $USER
    echo "请注销并重新登录以使更改生效，然后重新运行此脚本"
    exit 1
fi

# 生成随机密钥
SECRET_KEY=$(openssl rand -hex 16)
echo "生成的密钥: $SECRET_KEY"

# 更新docker-compose.yml中的密钥
sed -i "s/your_secret_key_here/$SECRET_KEY/g" docker-compose.yml

# 构建并启动容器
echo "构建并启动Docker容器..."
docker-compose up -d --build

echo "部署完成！应用现在应该在http://localhost或您的服务器IP上运行"
